package com.zline.foodraise.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.FragmentTransaction;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.umeng.update.UmengUpdateAgent;
import com.zline.foodraise.R;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.H5Params;
import com.zline.foodraise.entity.MomentBean;
import com.zline.foodraise.entity.MsgNoticeRedPointBean;
import com.zline.foodraise.entity.OrderRedPointBean;
import com.zline.foodraise.entity.RedPointBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.FragmentListener;
import com.zline.foodraise.ui.fragment.DynamicFragment;
import com.zline.foodraise.ui.fragment.DynamicFragment_;
import com.zline.foodraise.ui.fragment.EatFragment;
import com.zline.foodraise.ui.fragment.EatFragment_;
import com.zline.foodraise.ui.fragment.HomePageFragment;
import com.zline.foodraise.ui.fragment.HomePageFragment_;
import com.zline.foodraise.ui.fragment.MeFragment;
import com.zline.foodraise.ui.fragment.MeFragment_;
import com.zline.foodraise.util.FileUtils;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.TUtil;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.DimensionPixelOffsetRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by heshantao on 15/6/25.
 * 主界面
 */
@EActivity(R.layout.activity_main)
public class MainActivity extends ZlineActivity implements FragmentListener {
    private static final String LOG_TAG = MainActivity.class.getSimpleName();
    //整个底部
    @ViewById(R.id.main_bottom_tab_ll)
    LinearLayout bottom_ll;
    //筹
    @ViewById(R.id.main_tab_home_page)
    TextView home_tv;
    //吃
    @ViewById(R.id.main_tab_eat)
    TextView eat_tv;
    //动态
    @ViewById(R.id.main_tab_dynamic)
    TextView dynamic_tv;
    @ViewById(R.id.main_tab_dynamic_red_point)
    View dynamic_red_point;
    //我
    @ViewById(R.id.main_tab_me)
    TextView me_tv;
    @ViewById(R.id.main_tab_me_red_point)
    View me_red_point;
    @ViewById(R.id.main_fl)
    FrameLayout main_fl;
    private HomePageFragment homePageFragment;
    private EatFragment eatFragment;
    private DynamicFragment dynamicFragment;
    private MeFragment meFragment;
    private int lastTab = 0;
    long mExitTime;
    @Bean
    HttpUtil httpUtil;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpDataParsing httpDataParsing;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Pref
    AppPref_ appPref;
    //动态tab中是否点击放大图片
    boolean showPhotoView = true;
    //自动将dp转化为px
    @DimensionPixelOffsetRes(R.dimen.tab_bottom_height)
    int paddingBottom;
    //用于显示碎片下标
    @Extra
    int fragmentIndex;
    //是否退出登录
    @Extra
    boolean isLogOut = false;
    //最新的活动公告Id
    long noticeId;
    //最新的消息Id
    long msgId;
    //最新一条未支付筹订单Id
    long lastUnPayCfOrderId;
    // 最新一条未确认筹订单Id
    long lastUnConfirmedCfOrderId;
    //最新一条商家未处理筹订单Id
    long lastUnHandleCfOrderId;
    MsgNoticeRedPointBean msgNoticeRedPointBean;
    boolean msgNoticeRedPointGet = false;
    OrderRedPointBean orderRedPointBean;
    boolean orderRedPointGet = false;
    MomentBean momentBean;
    RedPointBean redPointBean;

    @AfterInject
    void callAfterInject() {
        UmengUpdateAgent.update(this);
        requestInitParamers();
    }

    @AfterViews
    void callAfterView() {
        if (appPref.userId().get() > 0) {
            requestRedPointInfo();
            requestDynamicList();
        }
    }

    //获得初始化参数，h5的根目录
    void requestInitParamers() {
        httpOperator.requestInitParams(httpUtil, getInitHandler);
        //主要用于在订单列表页中跳转到主页的操作
    }


    //获得初始化参数，h5的根目录的回调
    AsyncHttpResponseHandler getInitHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs____getInitHandler______" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        saveInitParams(response);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    gotoFragment();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            gotoFragment();
        }
    };

    //存储初始化参数
    void saveInitParams(JSONObject obj) {
        String rootUrl;
        H5Params params = httpDataParsing.getH5InitInfo(obj);
        rootUrl = params.getH5Domain();
        appPref.edit().rootUrl().put(rootUrl).apply();
    }


    //底部bottomFragment跳转
    void gotoFragment(){
        switch (fragmentIndex){
            case 0:
                initHomePageFragment();
                break;
            case 1:
                initEatFragment();
                break;
            default:
                break;
        }
    }


    //获取小红点信息(底部导航栏我)
    void requestRedPointInfo() {
        long cityId = appPref.cityId().get();
        httpOperator.requestMsgNoticeRedPointInfo(httpUtil, cityId, requestMsgNoticeRedPointInfoHandler);
        httpOperator.requestOrderRedPointInfo(httpUtil, requestOrderRedPointInfoHandler);
    }


    //获得消息活动公告小红点信息回调(底部导航栏我)
    AsyncHttpResponseHandler requestMsgNoticeRedPointInfoHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs____requestMsgNoticeRedPointInfoHandler______" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        msgNoticeRedPointBean = httpDataParsing.getRedPointInfo(response);
                        msgNoticeRedPointGet = true;
                        doSomeAfterRedPoint();
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };

    //获得订单小红点信息回调(底部导航栏我)
    AsyncHttpResponseHandler requestOrderRedPointInfoHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs____requestOrderRedPointInfoHandler______" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        orderRedPointBean = httpDataParsing.getOrderRedPointInfo(response);
                        orderRedPointGet = true;
                        doSomeAfterRedPoint();
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };

    //处理小红点情况
    void doSomeAfterRedPoint() {
        boolean showMeRedPoint = false;
        if (msgNoticeRedPointBean != null) {
            noticeId = msgNoticeRedPointBean.getLastNoticeId();
            msgId = msgNoticeRedPointBean.getLastSysPushId();
        }
        if (orderRedPointBean != null) {
            lastUnPayCfOrderId = orderRedPointBean.getLastUnPayCfOrderId();
            lastUnConfirmedCfOrderId = orderRedPointBean.getLastUnConfirmedCfOrderId();
            lastUnHandleCfOrderId = orderRedPointBean.getLastUnHandleCfOrderId();
        }
        if (msgNoticeRedPointGet && orderRedPointGet) {
            if (0 < lastUnPayCfOrderId
                    || 0 < lastUnConfirmedCfOrderId
                    || 0 < lastUnHandleCfOrderId
                    || appPref.lastMsgId().get() < msgId
                    || appPref.lastNoticeId().get() < noticeId) {
                showMeRedPoint = true;
            }
        } else if (msgNoticeRedPointGet) {
            if (appPref.lastMsgId().get() < msgId || appPref.lastNoticeId().get() < noticeId) {
                showMeRedPoint = true;
            }
        } else if (orderRedPointGet) {
            if (0< lastUnPayCfOrderId
                    || 0 < lastUnConfirmedCfOrderId
                    || 0< lastUnHandleCfOrderId) {
                showMeRedPoint = true;
            }
        }
        if (showMeRedPoint) {
            me_red_point.setVisibility(View.VISIBLE);
        }

    }


    //请求最新动态
    void requestDynamicList() {
        httpOperator.requstDynamicList(httpUtil, 1, 1, requestDynamicListHandler);
    }

    //获取动态列表回调
    AsyncHttpResponseHandler requestDynamicListHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestDynamicListHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        SparseArray<MomentBean> array = httpDataParsing.getDynamicList(response);
                        observerDynamicRedPoint(array);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };

    void observerDynamicRedPoint(SparseArray<MomentBean> momentArray) {
        momentBean = momentArray.get(0);
        if (momentBean != null) {
            long momentId = momentBean.getMomentId();
            if (appPref.momentId().get() < momentId) {
                dynamic_red_point.setVisibility(View.VISIBLE);
            } else {
                dynamic_red_point.setVisibility(View.GONE);
            }

        }

    }


    //首页
    private void initHomePageFragment() {
        LUtil.i(LOG_TAG, "___________homepage_________");
        if (homePageFragment == null) {
            homePageFragment = new HomePageFragment_().builder().build();
        }
        FragmentTransaction transaction = obtainFragmentTransaction();
        if (homePageFragment.isAdded()) {
            homePageFragment.onResume();
        } else {
            transaction.add(R.id.main_fl, homePageFragment);
        }
        showTab(1);
        unSelectBottomTab(lastTab);
        home_tv.setSelected(true);
        lastTab = 1;
        transaction.commit();
        if (isLogOut) {
            homePageFragment.clearUserInfo();
        }
    }

    //吃
    private void initEatFragment() {
        LUtil.i(LOG_TAG, "___________eatFragment_________");
        if (eatFragment == null) {
            eatFragment = new EatFragment_().builder().build();
        }
        FragmentTransaction transaction = obtainFragmentTransaction();
        if (eatFragment.isAdded()) {
            eatFragment.onResume();
        } else {
            transaction.add(R.id.main_fl, eatFragment);
        }
        showTab(2);
        unSelectBottomTab(lastTab);
        eat_tv.setSelected(true);
        lastTab = 2;
        transaction.commit();
    }


    //动态
    private void initDynamicFragment() {
        LUtil.i(LOG_TAG, "___________dynamic________");
        if (dynamicFragment == null) {
            dynamicFragment = new DynamicFragment_().builder().build();
            dynamicFragment.setFragmentListener(this);
        }
        FragmentTransaction transaction = obtainFragmentTransaction();
        if (dynamicFragment.isAdded()) {
            dynamicFragment.onResume();
        } else {
            transaction.add(R.id.main_fl, dynamicFragment);
        }
        showTab(3);
        unSelectBottomTab(lastTab);
        dynamic_tv.setSelected(true);
        lastTab = 3;
        transaction.commit();
    }

    // 我
    private void initMeFragment() {
        if (meFragment == null) {
            meFragment = new MeFragment_().builder().build();
            meFragment.setFragmentListener(this);
        }
        FragmentTransaction transaction = obtainFragmentTransaction();
        if (meFragment.isAdded()) {
            meFragment.onResume();
        } else {
            transaction.add(R.id.main_fl, meFragment);
        }

        if (msgNoticeRedPointBean == null) {
            msgNoticeRedPointBean = new MsgNoticeRedPointBean();
        }
        if (orderRedPointBean == null) {
            orderRedPointBean = new OrderRedPointBean();
        }
        if (redPointBean == null) {
            redPointBean = new RedPointBean(msgNoticeRedPointBean, orderRedPointBean);
        }
        meFragment.setRedPointBean(redPointBean);
        showTab(4);
        unSelectBottomTab(lastTab);
        me_tv.setSelected(true);
        lastTab = 4;
        transaction.commit();
    }


    //获得带动画效果的碎片事务
    private FragmentTransaction obtainFragmentTransaction() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.setCustomAnimations(R.animator.fade_in, R.animator.fade_out);
        return transaction;
    }

    //暂停前一个fragment
    private void pauseFragment() {
        if (lastTab > 0) {
            if (lastTab == 1) {
                homePageFragment.onPause();
            } else if (lastTab == 2) {
                eatFragment.onPause();
            } else if (lastTab == 3) {
                dynamicFragment.onPause();
            } else {
                meFragment.onPause();
            }
        }
    }

    //将其他tab 设置为未选中状态
    void unSelectBottomTab(int index) {
        switch (index) {
            case 1:
                home_tv.setSelected(false);
                break;
            case 2:
                eat_tv.setSelected(false);
                break;
            case 3:
                dynamic_tv.setSelected(false);
                break;
            case 4:
                me_tv.setSelected(false);
                break;
            default:
                break;
        }

    }

    //显示当前的fragment
    private void showTab(int index) {
        FragmentTransaction transaction = obtainFragmentTransaction();
        if (index == 1) {
            if (eatFragment != null) {
                transaction.hide(eatFragment);
            }
            if (dynamicFragment != null) {
                transaction.hide(dynamicFragment);
            }
            if (meFragment != null) {
                transaction.hide(meFragment);
            }
            transaction.show(homePageFragment);
        } else if (index == 2) {

            if (homePageFragment != null) {
                transaction.hide(homePageFragment);
            }
            if (dynamicFragment != null) {
                transaction.hide(dynamicFragment);
            }
            if (meFragment != null) {
                transaction.hide(meFragment);
            }

            transaction.show(eatFragment);
        } else if (index == 3) {

            if (homePageFragment != null) {
                transaction.hide(homePageFragment);
            }
            if (eatFragment != null) {
                transaction.hide(eatFragment);
            }
            if (meFragment != null) {
                transaction.hide(meFragment);
            }
            transaction.show(dynamicFragment);

        } else if (index == 4) {

            if (homePageFragment != null) {
                transaction.hide(homePageFragment);
            }
            if (eatFragment != null) {
                transaction.hide(eatFragment);
            }
            if (dynamicFragment != null) {
                transaction.hide(dynamicFragment);
            }
            transaction.show(meFragment);
        }
        transaction.commit();
    }

    //登录后的回调
    @OnActivityResult(Constant.MAIN_ACTIVITY_REQUEST_CODE)
    void onActivityResult(int resultCode) {
        switch (resultCode) {
            case Constant.LOGIN_RESULT_CODE:
                requestRedPointInfo();
                pauseFragment();
                home_tv.setSelected(true);
                initHomePageFragment();
                homePageFragment.setUserInfo();
                break;
            default:
                break;
        }
    }


    //底部切换
    @Click({R.id.main_tab_home_page, R.id.main_tab_eat, R.id.main_tab_dynamic, R.id.main_tab_me})
    void tabOnClick(View view) {
        switch (view.getId()) {
            case R.id.main_tab_home_page:
                pauseFragment();
                initHomePageFragment();
                break;
            case R.id.main_tab_eat:
                pauseFragment();
                initEatFragment();
                break;
            case R.id.main_tab_dynamic:
                if (appPref.userId().get() > 0) {
                    pauseFragment();
                    initDynamicFragment();
                } else {
                    LoginActivity_.intent(this).startForResult(Constant.MAIN_ACTIVITY_REQUEST_CODE);
                }
                break;
            case R.id.main_tab_me:
                if (appPref.userId().get() > 0) {
                    pauseFragment();
                    initMeFragment();
                } else {
                    LoginActivity_.intent(this).startForResult(Constant.MAIN_ACTIVITY_REQUEST_CODE);
                }
                break;
            default:
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        isLogOut = false;
    }


    //连续二次返回键退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!showPhotoView && dynamicFragment != null) {//当点击单张图片放大后，点击返回键图片回复原样
                dynamicFragment.onViewTap();
                return true;
            }
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                // 如果两次按键时间间隔大于2000毫秒，则不退出
                TUtil.showShort(this, R.string.back_out_hint);
                mExitTime = System.currentTimeMillis();// 更新mExitTime
            } else {
                clearWebCash();
                exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //退出APP
    void exitApp() {
        Intent intent = new Intent();
        intent.setAction(Constant.EXIT_ACTION);
        sendBroadcast(intent);
    }

    //清除webView 缓存
    void clearWebCash() {
        if (Build.VERSION.SDK_INT >= 19) {
            String appCachePath = this.getApplicationContext().
                    getDir(Constant.WEBVIEW, Context.MODE_PRIVATE).getPath() + "/" + Constant.CACHE1;
            FileUtils.deleteFile(appCachePath);
        } else {
            try {
                deleteDatabase("webview.db");
                deleteDatabase("webviewCache.db");
            } catch (Exception e) {
                e.printStackTrace();
            }
            String appCachePath = this.getApplicationContext()
                    .getCacheDir().getAbsolutePath() + "/" + Constant.WEBVIEW_CACHE;
            FileUtils.deleteFile(appCachePath);

        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearWebCash();
    }

    //影藏或者显示底部导航栏
    @Override
    public void inVokeActivity(boolean show) {
        showPhotoView = show;
        if (show) {
            bottom_ll.setVisibility(View.VISIBLE);
            main_fl.setPadding(0, 0, 0, paddingBottom);
        } else {
            bottom_ll.setVisibility(View.GONE);
            main_fl.setPadding(0, 0, 0, 0);
        }
    }

    @Override
    public void showMeRedPoint(boolean show) {
        if (show) {
            me_red_point.setVisibility(View.VISIBLE);
        } else {
            me_red_point.setVisibility(View.GONE);
        }
    }

    @Override
    public void showDynamicRedPoint(boolean show) {
        if (show) {
            dynamic_red_point.setVisibility(View.VISIBLE);
        } else {
            dynamic_red_point.setVisibility(View.GONE);
        }
    }
}
